/**
 * 
 */
package bingo.validation.validator;

import bingo.validation.ValidationException;
import bingo.validation.ValidationResult;
import bingo.validation.annotations.AnnotationValidator;
import bingo.validation.annotations.Regex;
import bingo.validation.util.RegexUtil;

/**
 * 正则表达式校验器，验证某个值是否符合指定的表达式
 */
public class RegexValidator extends AnnotationValidator<Regex> {
	
	private String expr;
	
	public RegexValidator(){
		this.setMessage("{name}不是有效的{exprName}");
	}

	@Override
	public void initialize(Regex check) {
		super.initialize(check);
		
		this.expr = check.expr();
	}

	/* (non-Javadoc)
	 * @see bingo.validation.annotations.AnnotationValidator#doValidate(java.lang.Object, java.lang.Object)
	 */
	@Override
	protected ValidationResult doValidate(Object objectToValidate, Object valueToValidate) throws ValidationException {
		
		if(null != valueToValidate){
			
			String value = valueToValidate.toString();
			
			if(RegexUtil.getInstance().isMatchString(value, expr)){
				return ValidationResult.pass();
			}
			
		}
		
		return ValidationResult.notPass(formatMessage());
	}

}
